package com.eascs.admin.o2o.loanAccount.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loanAccount.entity.O2oCollectFee;
import com.eascs.admin.o2o.loanAccount.service.IO2oCollectFeesService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

@RestController
@RequestMapping("/rcollectFees")
public class O2oCollectFeesRestController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(O2oCollectFeesRestController.class);

	@Reference
	SysOrgService sysOrgService;
	
	@Reference
	CustomerService customerService;
	@Autowired
	IO2oCollectFeesService o2oCollectFeesService;

	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	/**
	 * @Description:
	 * 				<p>
	 *               客户身份证和姓名是否一致
	 *               </p>
	 * @author yy
	 * @date 2017年7月14日 上午11:02:30
	 * @version V1.0
	 */
	@RequestMapping(value = "/check")
	public BaseRestResult<?> checkLoan(String idCard,String name ) {
		idCard = idCard.trim();
		
		CustomerEntity basic = customerService.queryCustomerEntityByIdCard(idCard);
		
		if (basic == null) {
			return BaseRestResult.warn("is_no_user");
		} else{
			if(!(basic.getCustomerName().equals(name.trim())&&basic.getIdNumber().equals(idCard.trim()))) {
				return BaseRestResult.warn("user_mismatch");
			}
			if(StringUtil.isEmpty(basic.getAccountId())){
				return BaseRestResult.warn("user_account_not_exit");
			}
		}
		
	
		return BaseRestResult.warn("success");

	}
	
	@RequestMapping(value = "/saveOrupdateCollectfees")
	public BaseRestResult<?> saveOrupdateCollectfees(O2oCollectFee entity) {
		
		if(entity.getCollectMoney()==null){
			return BaseRestResult.warn("打款金额不能为空");
		}
		
		
		
		if(entity.getBreakDate()==null){
			return BaseRestResult.warn("打款时间不能为空");
		}
		
		User user = UserHolder.getUser();
		ActOrgEntity actOrgEntity = null;
		
		com.eascs.workflow.common.vo.ModelResult<ActOrgEntity>  s = sysOrgService.getUniquePlatformWithUser(user.getNo());
		if(s.isSuccess()){
			actOrgEntity = s.getModel();
		}else{
			return BaseRestResult.warn(s.getErrMsg());
			
		}
				
		if(actOrgEntity!=null){
			entity.setLtdName(actOrgEntity.getOrgName());
			entity.setLtdCode(actOrgEntity.getUnitCode());
			entity.setLtd(actOrgEntity.getUnitNo());
		}
		if(entity.getId()==null){
			entity.setCreateDate(new Date());
			entity.setCreateId(user.getNo());
			entity.setCreateName(user.getCname());
			entity.setStatus(StatusContexts.O2O_NEW);
			entity.setIsDel(StatusContexts.O2O_NO);
			entity.setBillCode(o2oZxServiceImpl.buildCode("DK"));
			int count = o2oCollectFeesService.save(entity);
			if(count<0){
				logger.info("添加失败");
				return BaseRestResult.warn("添加失败");
			}else{
				return BaseRestResult.info("保存成功,请上传附件").andRedirect(UrlHelper.build("/collectFees/detail?id=" + entity.getId()));
			}
		}else{
			O2oCollectFee  entityj = o2oCollectFeesService.queryById(entity.getId());
			BeanUtils.copyProperties(entity,entityj );
			/*entityj.setUpdateId(user.getNo());
			entityj.setUpdateName(user.getCname());
			entityj.setUpdateDate(new Date());*/
			int count = o2oCollectFeesService.update(entityj);
			if(count<=0){
				logger.info("更新失败");
				return BaseRestResult.warn("更新失败");
			}
			return BaseRestResult.info("更新成功").andRedirect(UrlHelper.build("/collectFees/detail?id="+entityj.getId()+"&type=VIEW"));
		}
		
	}
	
	

	/**
	 * 附件上传 局部刷新DIV
	 * 
	 * @param loanapplyNo
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/uploadFile")
	public HtmlRestResult loanDetail(String id,String customer_id,String type) {
       
		ViewContext.put("datalistInfo", getDatalistInfo(id,type));
		ViewContext.put("customer_id", customer_id);
		ViewContext.put("id", id);
		ViewContext.put("type", type);
		return new HtmlRestResult("collectFees/uploadfileDiv");
	}
	
	
	@RequestMapping(value = "/skqr")
	public HtmlRestResult skqr(String id) {
       
		O2oCollectFee  entity = o2oCollectFeesService.queryById(id);
		ViewContext.put("entity", entity);
		return new HtmlRestResult("collectFees/skqr");
	}
	
	
	/**
	 * 附件列表
	 * @param loanapplyNo
	 * @return
	 */
	public PaginationInfo getDatalistInfo(String id,String type){
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(id);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles);

		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		if (type.equals("write")) {
			AjaxConfirmButton[] dealButton = new AjaxConfirmButton[] {
					new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			datalistInfo.setMoreButtons(dealButton);
		}
		return datalistInfo;
	}
	
	
	@RequestMapping(value = "/del")
	public BaseRestResult<?> del(String id) {
		O2oCollectFee  entity = o2oCollectFeesService.queryById(id);
		if (!StatusContexts.O2O_NEW.equals(entity.getStatus())) {
			return BaseRestResult.warn("该单流程已经启动，不能删除！");
		}
		entity.setIsDel(StatusContexts.O2O_YES);
		int count = o2oCollectFeesService.update(entity);
		if(count<=0){
			logger.error("更新失败");
			return BaseRestResult.warn("更新失败");
		}
		return BaseRestResult.info("删除成功").andRedirect(UrlHelper.build("/collectFees/index"));
	}
	
	
	
	/**
	 * @Title: startup
	 * @Description: 启动打款流程
	 * @author 张庆奇
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年12月5日 上午9:20:33
	 */
	@RequestMapping(value = "/startup")
	public BaseRestResult<String> startup(String id) {
		O2oCollectFee entity = o2oCollectFeesService.queryById(id);
		
		if (!StatusContexts.O2O_NEW.equals(entity.getStatus())) {
			return BaseRestResult.warn("该单流程已经启动");
		}
		
		if(entity.getCollectMoney()==null){
			return BaseRestResult.warn("打款金额不能为空");
		}
		
		if(entity.getBreakDate()==null){
			return BaseRestResult.warn("打款时间不能为空");
		}

		logger.info("个人账户收费对象：{}", entity);
		ModelResult<Boolean> modelResult = o2oCollectFeesService.startup(entity, "", "");
		if (modelResult.isSuccess() && modelResult.getModel()) {
			return BaseRestResult.info("提交成功").andRedirect(UrlHelper.build("/collectFees/index"));
		} else {
			logger.error("提交个人账户打款流程失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	
	
	}
}
